package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.domain.Member;
import cn.itcast.entity.Result;
import cn.itcast.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 使用手机号和验证码登录
     *
     * @param map
     * @param response
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response) {

        //取出手机号和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中取出验证码
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //对比验证码
        if (validateCode != null && code != null && validateCode.equals(code)) {

            //验证码匹配成功,根据手机号来判断是否是会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //不是则完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.insert(member);
            }

            //清空redis的key
            jedisPool.getResource().srem(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

            //登录成功,使用cookies跟踪用户
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            //路径
            cookie.setPath("/");
            //有效期30天
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //response对象发送cookie
            response.addCookie(cookie);
            //将用户存入redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
